package com.zhq.blog.manage.domain.controller.product;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhq.blog.core.domain.product.Note;
import com.zhq.blog.core.domain.search.NoteSearch;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/product/note/*")
public class NoteController extends BaseController {
	
	@RequestMapping()
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{
		NoteSearch search = null;
		if (viewState != null && !viewState.trim().equals("")) {
			search = (NoteSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), NoteSearch.class);
			return createModel("admin/product/note/list")
					.add("noteSearch", search)
					.add("viewState", viewState)
					.add("notePage",context.getNoteRepository().findAll(new Note().selectCondition(search),pageable));
		} else {
			search = new NoteSearch();
			return createModel("admin/product/note/list").add("noteSearch", search).add("viewState", "").add("notePage", context.getNoteRepository().findAll(new Note().selectCondition(search),pageable));

		}
	}
	
	@RequestMapping(value = "index", method = RequestMethod.POST)
	public BossModel index(NoteSearch search,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Sort.Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
		return createModel("admin/product/note/list")
				.add("notePage", context.getNoteRepository().findAll(new Note().selectCondition(search),pageable))
				.add("viewState",Base64.getEncoder().encodeToString(JSONObject.fromObject(search).toString().getBytes("UTF-8")));
	}

	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		context.getNoteRepository().delete(id);
		return createModel("admin/product/note/note_table").add("notePage",context.getNoteRepository().findAll(pageable)).add("viewState", viewState);
	}

}
